// 密码修改组件
Vue.component('profile-password', {
  data() {
    const validateConfirm = (rule, value, callback) => {
      if (value !== this.newPassword) {
        callback(new Error('新密码两次输入不一致'));
      } else {
        callback();
      }
    };
    return {
      password: '',
      newPassword: '',
      confirmPassword: '',
      rules: {
        password: [
          { required: true, message: '请输入原密码', trigger: 'change' }
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'change' }
        ],
        confirmPassword: [
          { required: true, message: '请确认新密码', trigger: 'change' },
          { validator: validateConfirm, trigger: 'change' }
        ]
      }
    };
  },
  template: `
    <div>
      <div style="font-size: 22px; font-weight: bold; margin-bottom: 18px;">修改密码</div>
      <el-form ref="form" :model="this" :rules="rules" label-width="120px">
        <el-form-item label="原密码" prop="password">
          <el-input v-model="password" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="newPassword" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="确认新密码" prop="confirmPassword">
          <el-input v-model="confirmPassword" type="password" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="changePassword">修改密码</el-button>
        </el-form-item>
      </el-form>
    </div>
  `,
  methods: {
    async changePassword() {
      const valid = await this.$refs.form.validate();
      if (!valid) return;
      
      try {
        const passwordData = {
          old_password: this.password,
          new_password: this.newPassword,
          confirm_password: this.confirmPassword
        };
        
        await authAPI.changePassword(passwordData);
        this.$message.success('密码修改成功，即将退出登录');
        
        // 清空表单
        this.password = '';
        this.newPassword = '';
        this.confirmPassword = '';
        
        // 重置表单验证状态
        this.$refs.form.resetFields();
        
        // 延迟2秒后退出到登录页面
        setTimeout(() => {
          // 清除本地存储的用户信息
          localStorage.removeItem('token');
          localStorage.removeItem('user');
          // 跳转到登录页面
          window.location.href = '/login';
        }, 2000);
        
      } catch (error) {
        console.error('密码修改失败:', error);
        this.$message.error(error.message || '密码修改失败');
      }
    }
  }
});